<template>
  <div class="button-container">
    <a-space wrap>
      <a-button type="primary" class="save-button" @click="saveJSON">保存</a-button>
    </a-space>
  </div>
  <div id="parent">
    <div class="child1">
      <FormBuilder v-bind:form="{display: 'form'}" v-bind:options="{}" v-on:change="change"></FormBuilder>
    </div>
    <div class="child2">
      <h2>json展示</h2>
      <pre>
        <div v-html="str"></div>
      </pre>
    </div>
  </div>
  </template>
<script setup name="formio" lang="ts">
import { FormBuilder } from '@formio/vue';
import { ref } from 'vue';
import axios from 'axios';

  let  str=ref()
  let saveStr=ref()
  function saveJSON(){
        // 示例：调用后端接口保存表单规则和配置
        axios.post('/api/saveForm', {
            rules: saveStr.value, //JSON字符串
          //JSON字符串
        }).then(response => {
            // 处理保存成功的逻辑
            console.log('表单保存成功', response.data);
        }).catch(error => {
            // 错误处理
            console.error('表单保存失败', error);
        });
    }
  function change(schema:Object){
    saveStr.value=JSON.stringify(schema)
    str.value=formatJson(JSON.stringify(schema))
  }

  function formatJson(jsonString:string) {
    const jsonParsed = JSON.parse(jsonString);
    const jsonStringified = JSON.stringify(jsonParsed, null, 4); // 缩进4个空格
    
    return jsonStringified.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
        function (match) {
            let cls = 'json-number';
            
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'json-key'; // 键名称
                } else {
                    cls = 'json-string'; // 字符串值
                }
            } else if (/true|false/.test(match)) {
                cls = 'json-boolean'; // 布尔型
            } else if (/null/.test(match)) {
                cls = 'json-null'; /* 空值   @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css');
                                             @import url('https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css');
                                             @import url('https://cdn.form.io/js/formio.full.min.css');*/
            }
            return '<span class="' + cls + '">' + match + '</span>';
        });
}


</script>

<style scoped>
 
    @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css');
    @import url('https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css');
    @import url('https://cdn.form.io/js/formio.full.min.css');
   #parent{
    display: flex;
    overflow: auto;
   }
   .child1{
    width: 70%;
    height: 100%;
    
   }
   .child2{
    width: 30%;
    height: 100%;
    margin-left: 60px;
   }
   .button-container {
    text-align: right; /* 将内容右对齐 */
    margin-top: 0px;  /* 添加一些顶部间距，使按钮不紧贴页面顶部 */
    margin-right: 20px;
}
</style>